package com.whut.mobilesafe.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.mobilesafe.R;
import com.whut.mobilesafe.domain.AppInfo;
import com.whut.mobilesafe.engine.AppInfoProvider;
import com.whut.mobilesafe.viewholder.HeaderHolder;
import com.whut.mobilesafe.viewholder.ListItemAppinfoHolder;

import java.util.ArrayList;


/**
 * 作    者:yubo.xiaoyubo
 * 时    间：2015/12/27 20:39
 * 版    本：1.0
 * 描    述：软件管理页面
 */
public class SoftwareAdminActivity extends Activity implements View.OnClickListener {

    private TextView tvTitle;
    private TextView tvInnerSpare;
    private TextView tvOutSpare;
    private ListView lvRoot;

    private TextView tvHeader;
    private ArrayList<AppInfo> appInfos;

    private AppInfo mCurrentInfo;

    private DataAdapter mDataAdapter;

    private ArrayList<AppInfo> mUserInfos;
    private ArrayList<AppInfo> mSystemInfos;

    private PopupWindow mPopupWindow;
    private View mPopupView;
    private AnimationSet mPopupAnimSet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soft_admin);

        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvInnerSpare = (TextView) findViewById(R.id.tv_inner_spare);
        tvOutSpare = (TextView) findViewById(R.id.tv_out_spare);
        lvRoot = (ListView) findViewById(R.id.lv_root);
        tvHeader = (TextView) findViewById(R.id.tv_header);

        String innerSpace = getSpace(Environment.getDataDirectory().getAbsolutePath());
        String outSpace = getSpace(Environment.getExternalStorageDirectory().getAbsolutePath());
        tvInnerSpare.setText("内存大小:" + innerSpace);
        tvOutSpare.setText("SD卡大小:" + outSpace);


        lvRoot.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //注意这句话不可以掉，否则回报空指针，原因是子线程的initData()方法还没有执行完
                if (mUserInfos != null && mSystemInfos != null) {
                    if (firstVisibleItem < mUserInfos.size() + 1) {
                        tvHeader.setText("用户应用(" + mUserInfos.size() + ")");
                    } else {
                        tvHeader.setText("系统应用(" + mSystemInfos.size() + ")");
                    }
                }
            }

        });

        lvRoot.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AppInfo appInfo = mDataAdapter.getItem(position);
                if (appInfo != null) {
                    //表示取到的不是标题栏
                    showPopuWindow(view);
                    mCurrentInfo = appInfo;
                }
            }
        });

        initData();
    }

    //显示小弹窗
    private void showPopuWindow(View view) {
        if (mPopupWindow == null) {
            mPopupView = View.inflate(this, R.layout.popup_item_appinfo, null);
            mPopupWindow = new PopupWindow(mPopupView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable());// 必须设置背景,这样点击返回键或者空白处才可以消失

            TextView tvUninstall = (TextView) mPopupView
                    .findViewById(R.id.tv_uninstall);
            TextView tvLaunch = (TextView) mPopupView
                    .findViewById(R.id.tv_launch);
            TextView tvShare = (TextView) mPopupView
                    .findViewById(R.id.tv_share);
            tvUninstall.setOnClickListener(this);
            tvLaunch.setOnClickListener(this);
            tvShare.setOnClickListener(this);

            // 弹窗动画效果
            // 渐变动画
            AlphaAnimation animAlpha = new AlphaAnimation(0, 1);
            animAlpha.setDuration(500);

            // 缩放动画
            ScaleAnimation animScale = new ScaleAnimation(0, 1, 0, 1,
                    Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,
                    0.5f);
            animScale.setDuration(500);

            mPopupAnimSet = new AnimationSet(true);
            mPopupAnimSet.addAnimation(animAlpha);
            mPopupAnimSet.addAnimation(animScale);
        }

        mPopupWindow.showAsDropDown(view, 50, -view.getHeight());
        mPopupView.startAnimation(mPopupAnimSet);
    }


    //初始化所有应用信息
    private void initData() {
        new Thread() {
            //子线程加载所有正在运行的应用
            @Override
            public void run() {
                appInfos = AppInfoProvider.getAllApp(getApplicationContext());
                mUserInfos = new ArrayList<AppInfo>();
                mSystemInfos = new ArrayList<AppInfo>();
                for (AppInfo info : appInfos) {
                    if (info.isUser()) {
                        mUserInfos.add(info);
                    } else {
                        mSystemInfos.add(info);
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDataAdapter = new DataAdapter();
                        lvRoot.setAdapter(mDataAdapter);
                    }
                });
            }
        }.start();
    }

    @Override
    public void onClick(View v) {
        mPopupWindow.dismiss();// 弹窗消失

        switch (v.getId()) {
            case R.id.tv_uninstall:
                System.out.println("卸载");
                uninstall();
                break;
            case R.id.tv_launch:
                System.out.println("启动");
                launch();
                break;
            case R.id.tv_share:
                System.out.println("分享");
                share();
                break;

            default:
                break;
        }
    }

    private void uninstall() {
        if (mCurrentInfo.isUser()) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DELETE);
            intent.setData(Uri.parse("package:" + mCurrentInfo.getName()));
            startActivityForResult(intent, 0);
        } else {
            Toast.makeText(this, "系统应用不可以卸载~~", Toast.LENGTH_SHORT).show();
        }
    }

    private void launch() {
        PackageManager packageManager = getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(mCurrentInfo.getName());
        if (intent != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, "找不到启动页面!", Toast.LENGTH_SHORT).show();
        }
    }

    private void share() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");// 分享纯文本
        intent.putExtra(Intent.EXTRA_TEXT,
                "分享给你一个很好的应用哦,下载地址:https://play.google.com/store/apps/details?id="
                        + mCurrentInfo.getName());
        startActivity(intent);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        initData();
    }

    class DataAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mUserInfos.size() + mSystemInfos.size() + 2;
        }

        @Override
        public AppInfo getItem(int position) {
            //标题栏
            if (position == 0 || position == mUserInfos.size() + 1) {
                return null;
            }
            if (position < mUserInfos.size() + 1) {
                return mUserInfos.get(position - 1);
            } else {
                return mSystemInfos.get(position - mUserInfos.size() - 2);
            }
        }


        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == mUserInfos.size() + 1) {
                return 0;//标题栏类型
            } else {
                return 1;//内容类型（包括用户和系统）
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            int type = getItemViewType(position);

            switch (type) {
                case 0://标题栏
                    HeaderHolder mHeaderHolder = null;
                    if (convertView == null) {
                        convertView = View.inflate(getApplicationContext(), R.layout.list_item_header, null);
                        mHeaderHolder = new HeaderHolder();

                        mHeaderHolder.tvHeader = (TextView) convertView.findViewById(R.id.tv_header);
                        convertView.setTag(mHeaderHolder);
                    } else {
                        mHeaderHolder = (HeaderHolder) convertView.getTag();
                    }

                    if (position == 0) {
                        mHeaderHolder.tvHeader.setText("用户应用(" + mUserInfos.size() + ")");
                    } else {
                        mHeaderHolder.tvHeader.setText("系统应用(" + mSystemInfos.size() + ")");
                    }
                    break;

                case 1://内容
                    ListItemAppinfoHolder mHolder = null;
                    if (convertView == null) {
                        mHolder = new ListItemAppinfoHolder();
                        convertView = View.inflate(getApplicationContext(), R.layout.list_item_appinfo, null);
                        mHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                        mHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                        mHolder.tvPosition = (TextView) convertView.findViewById(R.id.tv_position);

                        convertView.setTag(mHolder);
                    } else {
                        mHolder = (ListItemAppinfoHolder) convertView.getTag();
                    }

                    AppInfo appInfo = getItem(position);
                    mHolder.ivIcon.setImageDrawable(appInfo.getIcon());
                    mHolder.tvName.setText(appInfo.getName());
                    mHolder.tvPosition.setText(appInfo.getPosition());

                    break;
            }

            return convertView;
        }
    }


    //获取可用空间
    public String getSpace(String path) {
        StatFs statFs = new StatFs(path);

        long availableBlocksLong = statFs.getAvailableBlocks();
        int blockSize = statFs.getBlockSize();
        long result = availableBlocksLong * blockSize;
        return Formatter.formatFileSize(this, result);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
